<template>
  <view class="detail">
    <view class="header">
      <up-tabs
        :list="tabList"
        @click="handleTable"
        :activeStyle="{
          fontSize: '32rpx',
          fontWeight: '500',
          lineHeight: '32rpx',
          color: '#FFFFFF',
        }"
        :inactiveStyle="{
          fontFamily: ' Alibaba PuHuiTi 3.0',
          fontSize: '32rpx',
          fontWeight: 'normal',
          textAlign: 'center',
          color: '#BFBFBF',
        }"
      ></up-tabs>
    </view>
    <view v-if="detailType == 1">
      <bmsDetail
        :dataListSummaryDataBMS="dataListSummaryDataBMS"
        :dataListSummaryDataModuleBMS="dataListSummaryDataModuleBMS"
        :moduleType="moduleType"
      />
      <view class="module-chart">
        <moduleChart
          :chartTitle="t('equipmentDetail.socAndCurrentCurves')"
          ref="moduleChartRef"
          :summaryCurve="summaryCurve"
          @handleTime="getBmsDataCurve"
        />
      </view>
      <template v-if="moduleType">
        <!-- 单体电池电压 -->
        <voltageChart
          v-show="Object.keys(monomerVoltageChart).length !== 0"
          :chartTitle="t('equipmentDetail.singleCellVoltage')"
          :voltageChartData="monomerVoltageChart"
          :dataListSummaryDataModuleBMS="dataListSummaryDataModuleBMS"
          :type="1"
          class="module-chart"
        />
        <!-- 单体电池温度 -->
        <voltageChart
          v-show="Object.keys(temperatureChart).length !== 0"
          :chartTitle="t('equipmentDetail.cellTemperature')"
          :voltageChartData="temperatureChart"
          :type="2"
          :dataListSummaryDataModuleBMS="dataListSummaryDataModuleBMS"
          class="module-chart"
        />
      </template>
    </view>

    <view v-if="detailType == 2">
      <dcdcDetail
        v-if="!moduleType"
        :moduleType="moduleType"
        :dataListSummaryDataDCDC="dataListSummaryDataDCDC"
      />
      <view class="module-chart">
        <moduleChart
          ref="moduleChartRef"
          :summaryCurve="dataListDCDCusver"
          @handleTime="getDCDCCurver"
          :chartTitle="t('equipmentDetail.powerAndCurrentCurves')"
        />
      </view>
      <view v-if="moduleType" class="detail-dcdc-item">
        <up-row style="margin-top: 30rpx">
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackVoltage.png"
                mode=""
              />
              <view class="number">
                <view> {{ dataListModuleDataDCDC.highVoltSideVolt }} V</view>
                <view class="unit">
                  {{ t("equipmentDetail.highSideVoltage") }}
                </view>
              </view>
            </view>
          </up-col>
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackCurrent.png"
                mode=""
              />
              <view class="number">
                <view>
                  {{
                    formatCurrent(dataListSummaryDataDCDC.lowVoltSideCurr).value
                  }}

                  {{
                    formatCurrent(dataListSummaryDataDCDC.lowVoltSideCurr)
                      .templete
                  }}
                  <!-- {{ dataListModuleDataDCDC.lowVoltSideCurr }} A -->
                </view>
                <view class="unit">
                  {{ t("equipmentDetail.highSideCurrent") }}
                </view>
              </view>
            </view>
          </up-col>
        </up-row>
        <up-row style="margin-top: 30rpx">
          <up-col span="6">
            <view class="row-detail">
              <image class="row-detail-img" src="/static/kw-icon.png" mode="" />
              <view class="number">
                <view>
                  {{ formatPower(dataListModuleDataDCDC.highVoltSidePower) }}
                </view>
                <view class="unit">
                  {{ t("equipmentDetail.highSidePower") }}</view
                >
              </view>
            </view>
          </up-col>
          <up-col span="6">
            <view class="row-detail">
              <image class="row-detail-img" src="/static/kw-icon.png" mode="" />
              <view class="number">
                <view>
                  {{ formatPower(dataListModuleDataDCDC.lowVoltSidePower) }}
                </view>
                <view class="unit">{{
                  t("equipmentDetail.lowSidePower")
                }}</view>
              </view>
            </view>
          </up-col>
        </up-row>
        <up-row style="margin-top: 30rpx">
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackVoltage.png"
                mode=""
              />
              <view class="number">
                <view> {{ dataListModuleDataDCDC.lowVoltSideVolt }} V</view>
                <view class="unit">{{
                  t("equipmentDetail.lowSideVoltage")
                }}</view>
              </view>
            </view>
          </up-col>
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackCurrent.png"
                mode=""
              />
              <view class="number">
                <view>
                  {{
                    formatCurrent(dataListSummaryDataDCDC.lowVoltSidePower)
                      .value
                  }}

                  {{
                    formatCurrent(dataListSummaryDataDCDC.lowVoltSidePower)
                      .templete
                  }}

                  <!-- {{ dataListModuleDataDCDC.lowVoltSidePower }} A -->
                </view>
                <view class="unit">{{
                  t("equipmentDetail.lowSideCurrent")
                }}</view>
              </view>
            </view>
          </up-col>
        </up-row>
      </view>
    </view>

    <view v-if="detailType == 3">
      <mpptDetail
        v-if="!moduleType"
        :moduleType="moduleType"
        :dataListSummaryDataMPPT="dataListSummaryDataMPPT"
      />
      <view class="module-chart">
        <moduleChart
          :chartTitle="t('equipmentDetail.voltageAndCurrentCurves')"
          :summaryCurve="dataChartOfMpptCusver"
          @handleTime="getMpptCurve"
          ref="moduleChartRef"
        />
      </view>
      <view v-if="moduleType" class="detail-mppt-item">
        <up-row style="margin-top: 30rpx">
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackVoltage.png"
                mode=""
              />
              <view class="number">
                <view> {{ dataListDataMPPTModule.highVoltSideVolt }} V</view>
                <view class="unit">{{
                  t("equipmentDetail.highSideVoltage")
                }}</view>
              </view>
            </view>
          </up-col>
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackCurrent.png"
                mode=""
              />
              <view class="number">
                <view>
                  {{
                    formatCurrent(dataListDataMPPTModule.highVoltSideCurr).value
                  }}

                  {{
                    formatCurrent(dataListDataMPPTModule.highVoltSideCurr)
                      .templete
                  }}

                  <!-- {{dataListDataMPPTModule.highVoltSideCurr }} A -->
                </view>
                <view class="unit">{{
                  t("equipmentDetail.highSideCurrent")
                }}</view>
              </view>
            </view>
          </up-col>
        </up-row>
        <up-row style="margin-top: 30rpx">
          <up-col span="6">
            <view class="row-detail">
              <image class="row-detail-img" src="/static/kw-icon.png" mode="" />
              <view class="number">
                <view>
                  {{ formatPower(dataListDataMPPTModule.highVoltSidePower) }}
                </view>
                <view class="unit">{{
                  t("equipmentDetail.highSidePower")
                }}</view>
              </view>
            </view>
          </up-col>
          <up-col span="6">
            <view class="row-detail">
              <image class="row-detail-img" src="/static/kw-icon.png" mode="" />
              <view class="number">
                <view>
                  {{ formatPower(dataListDataMPPTModule.lowVoltSidePower) }}
                </view>
                <view class="unit">{{
                  t("equipmentDetail.lowSidePower")
                }}</view>
              </view>
            </view>
          </up-col>
        </up-row>
        <up-row style="margin-top: 30rpx">
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackVoltage.png"
                mode=""
              />
              <view class="number">
                <view> {{ dataListDataMPPTModule.lowVoltSideVolt }} V</view>
                <view class="unit">{{
                  t("equipmentDetail.lowSideVoltage")
                }}</view>
              </view>
            </view>
          </up-col>
          <up-col span="6">
            <view class="row-detail">
              <image
                class="row-detail-img"
                src="/static/batteryPackCurrent.png"
                mode=""
              />
              <view class="number">
                <view>
                  {{
                    formatCurrent(dataListDataMPPTModule.lowVoltSideCurr).value
                  }}
                  {{
                    formatCurrent(dataListDataMPPTModule.lowVoltSideCurr)
                      .templete
                  }}
                  <!-- {{ dataListDataMPPTModule.lowVoltSideCurr }} A -->
                </view>
                <view class="unit">{{
                  t("equipmentDetail.lowSideCurrent")
                }}</view>
              </view>
            </view>
          </up-col>
        </up-row>
      </view>
    </view>

    <view v-if="detailType == 4">
      <pcsDetail
        :moduleType="moduleType"
        :dataListSummaryDataPCS="dataListSummaryDataPCS"
        v-if="!moduleType"
      />
      <view class="module-chart">
        <moduleChart
          :chartTitle="t('equipmentDetail.powerCurves')"
          :summaryCurve="summaryCurveOfPcs"
          @handleTime="getPcsCur"
          ref="moduleChartRef"
        />
      </view>

      <view class="pcs-list" v-if="moduleType">
        <up-cell-group :border="false">
          <up-cell
            :title="t('equipmentDetail.acReactivePower')"
            :value="dataListModuleDataPCS.acReactivePower + 'kVar'"
          ></up-cell>

          <up-cell
            :title="t('equipmentDetail.acApparentPower')"
            :value="dataListModuleDataPCS.acSignPower + 'kWA'"
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.acPhaseAVoltage')"
            :value="dataListModuleDataPCS.acaPhaseVoltage + 'V'"
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.acPhaseBVoltage')"
            :value="dataListModuleDataPCS.acbPhaseVoltage + 'V'"
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.acCPhaseVoltage')"
            :value="dataListModuleDataPCS.accPhaseVoltage + 'V'"
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.acPhaseACurrent')"
            :value="
              formatCurrent(dataListModuleDataPCS.acaPhaseElec).value +
              formatCurrent(dataListModuleDataPCS.acaPhaseElec).templete
            "
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.acBPhaseCurrent')"
            :value="
              formatCurrent(dataListModuleDataPCS.acbPhaseElec).value +
              formatCurrent(dataListModuleDataPCS.acbPhaseElec).templete
            "
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.acCPhaseCurrent')"
            :value="
              formatCurrent(dataListModuleDataPCS.accPhaseElec).value +
              formatCurrent(dataListModuleDataPCS.accPhaseElec).templete
            "
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.acFrequency')"
            :value="dataListModuleDataPCS.acFrequency + 'Hz'"
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.dcVoltage')"
            :value="dataListModuleDataPCS.dcVoltage + 'V'"
          ></up-cell>
          <up-cell
            :title="t('equipmentDetail.dcCurrent')"
            :value="
              formatCurrent(dataListModuleDataPCS.dcElec).value +
              formatCurrent(dataListModuleDataPCS.dcElec).templete
            "
          ></up-cell>
        </up-cell-group>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, nextTick, provide } from "vue";
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import bmsDetail from "./components/bmsDetail.vue";
import pcsDetail from "./components/pcsDetail.vue";
import mpptDetail from "./components/mpptDetail.vue";
import dcdcDetail from "./components/dcdcDetail.vue";
const moduleChartRef = ref(null);
const summaryCurve = ref({});
import apis from "@/apis/index";
import {
  powerUnit,
  chargeUnit,
  calculateAverage,
  formatPowerUnitOfUnit,
  formatCurrentUnitOfUnit,
  formatPower,
  formatCurrent,
} from "@/utils/utils";
const dataListSummaryDataBMS = ref({});
const dataListSummaryDataModuleBMS = ref({});

const dataListSummaryDataDCDC = ref({});
const dataListModuleDataDCDC = ref();
const dataListDCDCusver = ref();

const dataListSummaryDataMPPT = ref({});
const dataListDataMPPTModule = ref({});
const dataChartOfMpptCusver = ref({});

const dataListSummaryDataPCS = ref({});
const dataListModuleDataPCS = ref({});

const tabList = ref([]);
const detailType = ref("");
const moduleType = ref(false);
const temperatureChart = ref({});
const monomerVoltageChart = ref({});
const summaryCurveOfPcs = ref({});
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const handleTable = (item) => {
  console.log("item", item);
  moduleNumber.value = item.index;
  moduleType.value = item.showMonomer;
  nextTick(() => {
    getPageData();
  });
};

const deliverName = ref("");
const moduleNumber = ref(0);
const queryParams = ref();

onLoad((options) => {
  queryParams.value = options;
  uni.setNavigationBarTitle({
    title: options.name,
  });
  detailType.value = options.type;
  switch (Number(options.type)) {
    case 1:
      deliverName.value = "BMS";
      break;
    case 2:
      deliverName.value = "DCDC";
      break;
    case 3:
      deliverName.value = "MPPT";
      break;
    case 4:
      deliverName.value = "PCS";
      break;
    default:
  }
  let obj = {
    name: t("equipmentDetail.summary"),
    showMonomer: false,
  };
  tabList.value.push(obj);
  for (let i = 0; i < options.moduleNumber; i++) {
    let obj = {
      name: deliverName.value + "-" + (i + 1),
      showMonomer: true,
    };
    tabList.value.push(obj);
  }
  nextTick(() => {
    getPageData();
  });
});
onPullDownRefresh(() => {
  // 下拉刷新时重新获取数据;
  getPageData(() => {
    // 数据获取完成后停止下拉刷新动画
    uni.stopPullDownRefresh();
  });
});
const getPageData = (callback) => {
  switch (Number(detailType.value)) {
    case 1:
      getBmsData();
      getBmsDataCurve();
      break;
    case 2:
      getDCDCData();
      getDCDCCurver();
      break;
    case 3:
      getMpptData();
      getMpptCurve();
      break;
    case 4:
      getPcsData();
      getPcsCur();
      break;
    default:
  }
  nextTick(() => {
    if (callback) {
      callback();
    }
  });
};
const setChartData = (data) => {
  let currTimeArr = [];
  let batteryPackSOCArr = [];
  let batteryPackElecArr = [];

  let batteryPackElecArrTest = [];
  data.forEach((item) => {
    currTimeArr.push(item.currTime);
    batteryPackSOCArr.push(item.batteryPackSOC);
    batteryPackElecArrTest.push(item.batteryPackElec);
  });

  const pinjin = calculateAverage(...batteryPackElecArrTest);

  const unit = formatCurrent(pinjin, 1).templete;

  data.forEach((item) => {
    batteryPackElecArr.push(
      formatCurrentUnitOfUnit(item.batteryPackElec, unit)
    );
  });

  if (
    currTimeArr.length > 0 &&
    batteryPackSOCArr.length > 0 &&
    batteryPackElecArr.length > 0
  ) {
    // 计算 Y 轴最大数值的字符长度
    const maxValue = Math.max(...batteryPackSOCArr, ...batteryPackElecArr);
    const maxLength = maxValue.toString().length;
    // 根据字符长度动态调整 grid 的 left 值
    const baseLeft = -2; // 基础 left 百分比
    const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
    const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%

    const chartOption = {
      title: {},
      legend: {
        icon: "rect",
        itemWidth: 12,
        itemHeight: 8,
        itemStyle: {
          borderRadius: 20, // 调整后的圆角值
          borderWidth: 0, // 设置边框宽度为0
        },
        textStyle: {
          // 设置图例文字的大小
          fontSize: 10,
          // 设置图例文字的颜色
          color: "#6e7180",
        },
        data: [
          {
            name: t("equipmentDetail.totalStackCurrent"),
            icon: "rect",
            itemStyle: {
              color: "#9670F9", // 对应储能功率折线图线条颜色
            },
          },
          {
            name: "SOC",
            icon: "rect",
            itemStyle: {
              color: "#097BFE", // 对应储能功率折线图线条颜色
            },
          },
        ],
      },
      xAxis: {
        type: "category",
        boundaryGap: false, // 确保折线图的起点和终点与坐标轴的两端对齐
        data: currTimeArr,
      },
      yAxis: [
        {
          type: "value",
          position: "right", // 将该纵轴放置在右侧
          name: unit,
          nameLocation: "end", // 使单位名称在末端显示
          nameTextStyle: {
            padding: [0, 0, 0, 30], // 设置上下左右边距，这里设置左右边距为 10
          },
          axisTick: {
            lineStyle: {
              type: "dashed", // 设置第一个 y 轴刻度线为虚线
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed", // 设置第一个 y 轴网格线为虚线
            },
          },
          axisLabel: {
            show: true,
            color: "#6e7180",
          },
          axisLine: {
            show: false,
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
              color: "#6e7180",
            },
          },
        },
        {
          type: "value",
          name: "%",
          position: "left", // 将该纵轴放置在左侧
          nameTextStyle: {
            color: "#6e7180", // 纵轴名称文字颜色
          },
          axisTick: {
            lineStyle: {
              type: "dashed", // 设置第一个 y 轴刻度线为虚线
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed", // 设置第一个 y 轴网格线为虚线
              color: "#6e7180", // 修改 x 轴网格横线颜色为红色
            },
          },
          axisLabel: {
            show: true,
            color: "#6e7180",
            formatter: "{value}", // 显示百分比格式
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#6e7180",
            },
          },
          // min: 0, // 最小值
          // max: 100, // 最大值
        },
      ],
      series: [
        {
          name: t("equipmentDetail.totalStackCurrent"),
          data: batteryPackElecArr,
          type: "line",
          smooth: true,
          yAxisIndex: 1, // 使用第一个 y 轴（左侧）
          symbol: "none", // 取消小圆点
          lineStyle: {
            color: "#9670F9", // 修改线条颜色为红色
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#554A98", // 渐变起始颜色
                },
                {
                  offset: 1,
                  color: "#23304C", // 渐变结束颜色
                },
              ],
            },
          },
        },
        {
          name: "SOC",
          yAxisIndex: 0, // 使用第一个 y 轴（左侧）
          data: batteryPackSOCArr,
          type: "line",
          smooth: true,
          lineStyle: {
            color: "#097BFE", // 修改线条颜色为红色
          },
          symbol: "none", // 取消小圆点
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#0E55AB", // 渐变起始颜色
                },
                {
                  offset: 1,
                  color: "#132238", // 渐变结束颜色
                },
              ],
            },
          },
        },
      ],
      tooltip: {
        show: true,
        trigger: "axis",
        position: function (point, params, dom, rect, size) {
          // point: 鼠标位置，格式为 [x, y]
          // params: 提示框所对应的数据项
          // dom: 提示框的 DOM 节点
          // rect: 图表的 DOM 节点的矩形框信息
          // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
          let x = point[0];
          let y = point[1];
          let viewWidth = size.viewSize[0];
          let viewHeight = size.viewSize[1];
          let boxWidth = size.contentSize[0];
          let boxHeight = size.contentSize[1];

          // 确保 tooltip 在页面内完全显示
          if (x + boxWidth > viewWidth) {
            x = viewWidth - boxWidth;
          }
          if (y - boxHeight < 0) {
            y = boxHeight;
          }
          return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
        },
        backgroundColor: "#fff", // 设置背景颜色为白色
        borderColor: "#ccc", // 设置边框颜色
        borderWidth: 1, // 设置边框宽度
        extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
        formatter: function (params) {
          let xAxisValue = params[0].axisValue; // 获取 x 轴时间
          let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行

          params.forEach(function (param) {
            if (param.seriesName == t("equipmentDetail.totalStackCurrent")) {
              tooltipStr += `${param.seriesName}: ${param.value} ${unit} \n`;
            } else {
              tooltipStr += `${param.seriesName}: ${param.value} % \n`;
            }
          });
          return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
        },
      },
      grid: {
        top: "12%", // 上边距
        right: "2%", // 右边距
        bottom: "1%", // 下边距
        left: newLeft, // 左边距
        containLabel: true, // 是否包含坐标轴的标签
      },
      dataZoom: [
        // {
        //   type: "inside", // 内部缩放
        //   xAxisIndex: 0,
        //   start: 0,
        //   end: (7 / currTimeArr.length) * 100,
        //   zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
        //   moveOnMouseMove: true, // 允许鼠标拖动
        //   moveOnMouseWheel: false, // 禁止鼠标滚轮移动
        // },
      ],
    };
    summaryCurve.value = chartOption;
  } else {
    summaryCurve.value = {};
  }
};

// 判断每根柱子左边的数据是否有相等的

const getBmsDataCurve = () => {
  nextTick(() => {
    if (moduleNumber.value == 0) {
      let params = {
        siteId: queryParams.value.siteId,
        slaveId: queryParams.value.slaveId,
        currTime: moduleChartRef.value.getTimeJson(),
      };
      apis.getBmsCurve(params).then((res) => {
        if (res.code == 200) {
          setChartData(res.data);
        }
      });
    } else {
      console.log("获取模块相关数据。/。/。/。/。/");
      let params = {
        siteId: queryParams.value.siteId,
        slaveId: queryParams.value.slaveId,
        bmsId: moduleNumber.value,
        currTime: moduleChartRef.value.getTimeJson(),
      };
      apis.getBmsModuleCurve(params).then((res) => {
        if (res.code == 200) {
          setChartData(res.data);
        }
      });
    }
  });
};
const checkLeftDataEquality = (data) => {
  var result = [];
  for (var i = 0; i < data.length; i++) {
    var currentValue = data[i];
    var hasEqual = false;
    for (var j = 0; j < i; j++) {
      if (data[j] === currentValue) {
        hasEqual = true;
        break;
      }
    }
    result.push(hasEqual);
  }
  return result;
};

const setMonomerChart = (data, unit) => {
  let indexArr = data.map((item, index) => {
    return index + 1;
  });
  let hasEqualLeftData = checkLeftDataEquality(data);
  const max = Math.max(...data);
  const min = Math.min(...data);
  if (max && min) {
    let chart = {
      title: {},
      xAxis: {
        type: "category",
        data: indexArr,
        boundaryGap: true, // 确保柱子紧贴刻度线
      },
      yAxis: [
        {
          type: "value",
          axisLabel: {
            show: true,
            color: "#6e7180",
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#6e7180", // 修改 x 轴网格横线颜色为红色
            },
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#6e7180",
            },
          },
        },
      ],

      grid: {
        top: "12%", // 上边距
        right: "6%", // 右边距
        bottom: "1%", // 下边距
        left: "6%", // 左边距
        containLabel: true, // 是否包含坐标轴的标签
      },

      series: [
        {
          type: "bar", // 修改为柱状图
          data: data,
          label: {
            show: true,
            position: "top",
            formatter: function (params) {
              if (
                (params.value == max || params.value == min) &&
                !hasEqualLeftData[params.dataIndex]
              ) {
                return params.value;
              }
              return "";
            },
            color: "#ffffff",
          },
          itemStyle: {
            // 柱子样式
            // color: "#64B7F6",
            color: function (params) {
              if (params.value == max && !hasEqualLeftData[params.dataIndex]) {
                return "orange"; // 最大值柱子颜色设为橙色
              } else if (
                params.value == min &&
                !hasEqualLeftData[params.dataIndex]
              ) {
                return "cyan"; // 最小值柱子颜色设为青色
              }
              return "#64B7F6"; // 其他柱子颜色
            },
          },
          barWidth: "60%", // 缩小柱子宽度，可根据实际情况调整数值
        },
      ],
      tooltip: {
        show: true,
        trigger: "axis",
        position: function (point, params, dom, rect, size) {
          // point: 鼠标位置，格式为 [x, y]
          // params: 提示框所对应的数据项
          // dom: 提示框的 DOM 节点
          // rect: 图表的 DOM 节点的矩形框信息
          // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
          let x = point[0];
          let y = point[1];
          let viewWidth = size.viewSize[0];
          let viewHeight = size.viewSize[1];
          let boxWidth = size.contentSize[0];
          let boxHeight = size.contentSize[1];

          // 确保 tooltip 在页面内完全显示
          if (x + boxWidth > viewWidth) {
            x = viewWidth - boxWidth;
          }
          if (y - boxHeight < 0) {
            y = boxHeight;
          }

          return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
        },
        backgroundColor: "#fff", // 设置背景颜色为白色
        borderColor: "#ccc", // 设置边框颜色
        borderWidth: 1, // 设置边框宽度
        extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
        formatter: function (params) {
          let xAxisValue = params[0].axisValue; // 获取 x 轴时间
          let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
          params.forEach(function (param) {
            tooltipStr += `${param.value + " " + unit} `;
          });
          return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
        },
      },
      dataZoom: [
        {
          type: "inside", // 内部缩放
          xAxisIndex: 0,
          start: 0,
          end: (20 / indexArr.length) * 100, // 默认展示前 6 个数据
          zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
          moveOnMouseMove: true, // 允许鼠标拖动
          moveOnMouseWheel: false, // 禁止鼠标滚轮移动
        },
      ],
    };
    return chart;
  } else {
    return {};
  }
};
// const setMonomerChart = (data, unit) => {
//   const max = Math.max(...data);
//   const min = Math.min(...data);
//   let xAxis = ["最大", "最小"];
//   if (max && min) {
//     let chart = {
//       title: {},
//       xAxis: {
//         type: "category",
//         data: xAxis,
//         boundaryGap: true, // 确保柱子紧贴刻度线
//       },
//       yAxis: [
//         {
//           type: "value",
//           axisLabel: {
//             show: true,
//             color: "#6e7180",
//           },
//           axisTick: {
//             lineStyle: {
//               type: "dashed", // 设置 y 轴刻度线为虚线
//             },
//           },
//           splitLine: {
//             show: true,
//             lineStyle: {
//               type: "dashed", // 设置 y 轴刻度线为虚线
//               color: "#6e7180", // 修改 x 轴网格横线颜色为红色
//             },
//           },
//           axisTick: {
//             lineStyle: {
//               type: "dashed", // 设置 y 轴刻度线为虚线
//             },
//           },
//           axisLine: {
//             show: true,
//             lineStyle: {
//               type: "dashed", // 设置 y 轴刻度线为虚线
//               color: "#6e7180",
//             },
//           },
//         },
//       ],

//       grid: {
//         top: "12%", // 上边距
//         right: "6%", // 右边距
//         bottom: "1%", // 下边距
//         left: "6%", // 左边距
//         containLabel: true, // 是否包含坐标轴的标签
//       },

//       series: [
//         {
//           type: "bar", // 修改为柱状图
//           data: [max, min],
//           label: {
//             show: true, // 显示标签
//             position: "top", // 标签位置在顶部
//             formatter: "{c}", // 标签内容为数据值
//             color: "#ffffff", // 标签文字颜色
//             fontSize: 12, // 标签文字大小
//           },
//           itemStyle: {
//             // 为每个柱子设置不同的颜色
//             normal: {
//               color: function (params) {
//                 var colorList = ["#9670F9", "#097BFE"];
//                 return colorList[params.dataIndex];
//               },
//             },
//           },
//           barWidth: "60%", // 缩小柱子宽度，可根据实际情况调整数值
//         },
//       ],

//       // dataZoom: [
//       //   {
//       //     type: "inside", // 内部缩放
//       //     xAxisIndex: 0,
//       //     start: 0,
//       //     end: (7 / indexArr.length) * 100, // 默认展示前 6 个数据
//       //     zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
//       //     moveOnMouseMove: true, // 允许鼠标拖动
//       //     moveOnMouseWheel: false, // 禁止鼠标滚轮移动
//       //   },
//       // ],
//     };
//     return chart;
//   }
// };
const getBmsData = () => {
  if (moduleNumber.value == 0) {
    apis
      .getBmsSummary({
        siteId: queryParams.value.siteId,
        slaveId: queryParams.value.slaveId,
      })
      .then((res) => {
        if (res.code == 200) {
          dataListSummaryDataBMS.value = res.data;
        }
      });
  } else {
    console.log("获取模块数据");
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
      bmsId: moduleNumber.value,
    };
    apis.getBmsModuleApiData(params).then((res) => {
      if (res.code == 200) {
        dataListSummaryDataModuleBMS.value = res.data;
        // 单体电池电压
        if (res.data.singleVoltage && res.data.singleVoltage.length > 0) {
          monomerVoltageChart.value = setMonomerChart(
            res.data.singleVoltage,
            " V"
          );
        } else {
          monomerVoltageChart.value = {};
        }
        // 单体电池温度
        if (
          res.data.singleTemperature &&
          res.data.singleTemperature.length > 0
        ) {
          temperatureChart.value = setMonomerChart(
            res.data.singleTemperature,
            "  ℃"
          );
        } else {
          temperatureChart.value = {};
        }
      }
    });
  }
};

const getDCDCData = () => {
  if (moduleNumber.value == 0) {
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
    };
    apis.getDcdcSummary(params).then((res) => {
      console.log("DCDC", res);
      if (res.code == 200) {
        dataListSummaryDataDCDC.value = res.data;
      }
    });
  } else {
    let params = {
      dcdcId: moduleNumber.value,
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
    };
    apis.getDcdcModuleData(params).then((res) => {
      if (res.code == 200) {
        console.log("dcdc模块数据", res.data);
        dataListModuleDataDCDC.value = res.data;
      }
    });
  }
};

const getDCDCCurver = () => {
  if (moduleNumber.value == 0) {
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
      currTime: moduleChartRef.value.getTimeJson(),
    };
    apis.getDcdcCurve(params).then((res) => {
      if (res.code == 200) {
        dataListDCDCusver.value = setDcdcCurve(res.data);
      }
    });
  } else {
    let params = {
      currTime: moduleChartRef.value.getTimeJson(),
      dcdcId: moduleNumber.value,
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
    };
    apis.getDcdcModuleCurve(params).then((res) => {
      if (res.code == 200) {
        dataListDCDCusver.value = setDcdcCurve(res.data);
      }
    });
  }
};
const setDcdcCurve = (data) => {
  let currTimeArr = [];
  let lowVoltSideCurrArrTest = []; // 低压侧电流
  let lowVoltSidePowerArrTest = []; // 低压侧功率
  data.forEach((item) => {
    // 电流
    lowVoltSideCurrArrTest.push(Number(item.lowVoltSideCurr));
    // 功率
    lowVoltSidePowerArrTest.push(Number(item.lowVoltSidePower));
  });
  // 功率平均值
  let powerAverage = calculateAverage(...lowVoltSidePowerArrTest);
  // 电流平均值
  let currentAverage = calculateAverage(...lowVoltSideCurrArrTest);

  // 功率
  let getPowerUnit = powerUnit(powerAverage, 1);
  // 电流
  let currentUnit = formatCurrent(currentAverage).templete;

  let lowVoltSideCurrArr = []; // 低压侧电流
  let lowVoltSidePowerArr = []; // 低压侧功率

  data.forEach((item) => {
    currTimeArr.push(item.currTime);
    console.log("item.currentUnit", currentUnit);
    lowVoltSideCurrArr.push(
      formatCurrentUnitOfUnit(Number(item.lowVoltSideCurr), currentUnit)
    );
    lowVoltSidePowerArr.push(
      formatPowerUnitOfUnit(Number(item.lowVoltSidePower), getPowerUnit)
    );
  });
  console.log("lowVoltSideCurrArr", lowVoltSideCurrArr);
  if (
    currTimeArr.length > 0 &&
    lowVoltSideCurrArr.length > 0 &&
    lowVoltSidePowerArr.length > 0
  ) {
    // 计算 Y 轴最大数值的字符长度
    const maxValue = Math.max(...lowVoltSideCurrArr, ...lowVoltSidePowerArr);
    const maxLength = maxValue.toString().length;
    // 根据字符长度动态调整 grid 的 left 值
    const baseLeft = -2; // 基础 left 百分比
    const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
    const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
    // 统一 Y 轴刻度范围
    // const minValue = Math.min(...lowVoltSideCurrArr, ...lowVoltSidePowerArr);
    // const maxYValue = Math.max(...lowVoltSideCurrArr, ...lowVoltSidePowerArr);
    return {
      title: [],
      legend: {
        icon: "rect",
        itemWidth: 12,
        itemHeight: 8,
        right: "5%",
        itemStyle: {
          borderRadius: 20, // 调整后的圆角值
          borderWidth: 0, // 设置边框宽度为0
        },
        textStyle: {
          // 设置图例文字的大小
          fontSize: 10,
          // 设置图例文字的颜色
          color: "#6e7180",
        },
        data: [
          {
            name: t("equipmentDetail.lowSideCurrent"),
            icon: "rect",
            itemStyle: {
              color: "#097BFE", // 对应储能功率折线图线条颜色
            },
          },
          {
            name: t("equipmentDetail.lowSidePower"),
            icon: "rect",
            itemStyle: {
              color: "#9670F9", // 对应储能功率折线图线条颜色
            },
          },
        ],
      },
      xAxis: {
        type: "category",
        boundaryGap: false, // 确保折线图的起点和终点与坐标轴的两端对齐
        data: currTimeArr,
      },

      yAxis: [
        {
          type: "value",
          name: getPowerUnit,
          position: "left",
          axisLabel: {
            show: true,
            color: "#6e7180",
          },
          axisTick: {
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
              color: "#6e7180", // 修改 x 轴网格横线颜色为红色
            },
          },

          axisLine: {
            show: true,
            lineStyle: {
              color: "#6e7180",
            },
          },
          // min: minValue, // 统一最小值
          // max: maxYValue, // 统一最大值
          // splitNumber: 5, // 统一刻度间隔
        },
        {
          type: "value",
          name: currentUnit,
          position: "right", // 将该纵轴放置在右侧
          axisLabel: {
            show: true,
            color: "#6e7180",
          },
          axisTick: {
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
              color: "#6e7180", // 修改 x 轴网格横线颜色为红色
            },
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#6e7180",
            },
          },
          // min: minValue, // 统一最小值
          // max: maxYValue, // 统一最大值
          // splitNumber: 5, // 统一刻度间隔
        },
      ],
      series: [
        {
          // 电流
          name: t("equipmentDetail.lowSideCurrent"),
          data: lowVoltSideCurrArr,
          yAxisIndex: 1, // 左侧 Y 轴

          type: "line",
          smooth: true,
          lineStyle: {
            color: "#097BFE", // 修改线条颜色为红色
          },
          symbol: "none", // 取消小圆点
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#3A63BB", // 渐变起始颜色
                },
                {
                  offset: 1,
                  color: "#13253F", // 渐变结束颜色
                },
              ],
            },
          },
        },
        {
          // 功率
          name: t("equipmentDetail.lowSidePower"),
          data: lowVoltSidePowerArr,
          yAxisIndex: 0, // 左侧 Y 轴
          type: "line",
          smooth: true,
          lineStyle: {
            color: "#9670F9", // 修改线条颜色为红色
          },
          symbol: "none", // 取消小圆点
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#544995", // 渐变起始颜色
                },
                {
                  offset: 1,
                  color: "#25314D", // 渐变结束颜色
                },
              ],
            },
          },
        },
      ],
      tooltip: {
        show: true,
        trigger: "axis",
        position: function (point, params, dom, rect, size) {
          // point: 鼠标位置，格式为 [x, y]
          // params: 提示框所对应的数据项
          // dom: 提示框的 DOM 节点
          // rect: 图表的 DOM 节点的矩形框信息
          // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
          let x = point[0];
          let y = point[1];
          let viewWidth = size.viewSize[0];
          let viewHeight = size.viewSize[1];
          let boxWidth = size.contentSize[0];
          let boxHeight = size.contentSize[1];

          // 确保 tooltip 在页面内完全显示
          if (x + boxWidth > viewWidth) {
            x = viewWidth - boxWidth;
          }
          if (y - boxHeight < 0) {
            y = boxHeight;
          }

          return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
        },
        backgroundColor: "#fff", // 设置背景颜色为白色
        borderColor: "#ccc", // 设置边框颜色
        borderWidth: 1, // 设置边框宽度
        extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
        formatter: function (params) {
          let xAxisValue = params[0].axisValue; // 获取 x 轴时间
          let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
          params.forEach(function (param) {
            if (param.seriesName === t("equipmentDetail.lowSideCurrent")) {
              // 确保效率数据后面带有 % 单位
              tooltipStr += `${param.seriesName}: ${param.value} ${currentUnit} \n`;
            } else {
              tooltipStr += `${param.seriesName}: ${param.value} ${getPowerUnit} \n`;
            }
          });
          return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
        },
      },
      grid: {
        top: "18%", // 上边距
        right: "2%", // 右边距
        bottom: "1%", // 下边距
        left: newLeft, // 左边距
        containLabel: true, // 是否包含坐标轴的标签
      },
      dataZoom: [
        // {
        //   type: "inside", // 内部缩放
        //   xAxisIndex: 0,
        //   start: 0,
        //   end: (7 / currTimeArr.length) * 100,
        //   zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
        //   moveOnMouseMove: true, // 允许鼠标拖动
        //   moveOnMouseWheel: false, // 禁止鼠标滚轮移动
        // },
      ],
    };
  } else {
    return {};
  }
};

const setMpptCurve = (data) => {
  let currTimeArr = [];
  let lowVoltSideCurrArr = []; // 低压侧电流
  let lowVoltSideCurrArrTest = []; // 低压侧电流
  let lowVoltSideVoltArr = []; // 低压侧电压
  data.forEach((item) => {
    currTimeArr.push(item.currTime);
    lowVoltSideCurrArrTest.push(item.lowVoltSideCurr);
    lowVoltSideVoltArr.push(item.lowVoltSideVolt);
  });

  let currentAverage = calculateAverage(...lowVoltSideCurrArrTest);
  let currentUnit = formatCurrent(currentAverage).templete;

  data.forEach((item) => {
    lowVoltSideCurrArr.push(
      formatCurrentUnitOfUnit(item.lowVoltSideCurr, currentUnit)
    );
  });
  console.log("lowVoltSideVoltArr", lowVoltSideVoltArr);
  // 计算 Y 轴最大数值的字符长度
  const maxValue = Math.max(...lowVoltSideCurrArr, ...lowVoltSideVoltArr);
  const maxLength = maxValue.toString().length;
  // 根据字符长度动态调整 grid 的 left 值
  const baseLeft = -2; // 基础 left 百分比
  const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
  const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
  if (
    currTimeArr.length > 0 &&
    lowVoltSideCurrArr.length > 0 &&
    lowVoltSideVoltArr.length > 0
  ) {
    return {
      title: {},
      legend: {
        icon: "rect",
        itemWidth: 12,
        itemHeight: 8,
        right: "5%",
        itemStyle: {
          borderRadius: 20, // 调整后的圆角值
          borderWidth: 0, // 设置边框宽度为0
        },
        textStyle: {
          // 设置图例文字的大小
          fontSize: 10,
          // 设置图例文字的颜色
          color: "#6e7180",
        },
        data: [
          {
            name: t("equipmentDetail.lowSideVoltage"),
            icon: "rect",
            itemStyle: {
              color: "#097BFE", // 对应储能功率折线图线条颜色
            },
          },
          {
            name: t("equipmentDetail.lowSideCurrent"),
            icon: "rect",
            itemStyle: {
              color: "#9670F9", // 对应储能功率折线图线条颜色
            },
          },
        ],
      },
      xAxis: {
        type: "category",
        boundaryGap: false, // 确保折线图的起点和终点与坐标轴的两端对齐
        data: currTimeArr,
      },
      yAxis: [
        // 电压
        {
          type: "value",
          name: "V",
          position: "left",
          axisLabel: {
            show: true,
            color: "#6e7180",
          },
          axisTick: {
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
              color: "#6e7180", // 修改 x 轴网格横线颜色为红色
            },
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#6e7180",
            },
          },
        },
        // 电流
        {
          type: "value",
          name: currentUnit,
          position: "right", // 将该纵轴放置在右侧
          axisLabel: {
            show: true,
            color: "#6e7180",
          },
          axisTick: {
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
            },
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: "dashed", // 设置 y 轴刻度线为虚线
              color: "#6e7180", // 修改 x 轴网格横线颜色为红色
            },
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: "#6e7180",
            },
          },
        },
      ],
      series: [
        {
          // 电压
          name: t("equipmentDetail.lowSideVoltage"),
          data: lowVoltSideVoltArr,
          yAxisIndex: 0, // 左侧 Y 轴
          type: "line",
          smooth: true,
          lineStyle: {
            color: "#097BFE", // 修改线条颜色为红色
          },
          symbol: "none", // 取消小圆点
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#3A63BB", // 渐变起始颜色
                },
                {
                  offset: 1,
                  color: "#13253F", // 渐变结束颜色
                },
              ],
            },
          },
        },
        {
          // 电流
          name: t("equipmentDetail.lowSideCurrent"),
          data: lowVoltSideCurrArr,
          yAxisIndex: 1, // 左侧 Y 轴
          type: "line",
          smooth: true,
          lineStyle: {
            color: "#9670F9", // 修改线条颜色为红色
          },
          symbol: "none", // 取消小圆点
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: "#544995", // 渐变起始颜色
                },
                {
                  offset: 1,
                  color: "#25314D", // 渐变结束颜色
                },
              ],
            },
          },
        },
      ],
      tooltip: {
        show: true,
        trigger: "axis",
        position: function (point, params, dom, rect, size) {
          // point: 鼠标位置，格式为 [x, y]
          // params: 提示框所对应的数据项
          // dom: 提示框的 DOM 节点
          // rect: 图表的 DOM 节点的矩形框信息
          // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
          let x = point[0];
          let y = point[1];
          let viewWidth = size.viewSize[0];
          let viewHeight = size.viewSize[1];
          let boxWidth = size.contentSize[0];
          let boxHeight = size.contentSize[1];

          // 确保 tooltip 在页面内完全显示
          if (x + boxWidth > viewWidth) {
            x = viewWidth - boxWidth;
          }
          if (y - boxHeight < 0) {
            y = boxHeight;
          }

          return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
        },
        backgroundColor: "#fff", // 设置背景颜色为白色
        borderColor: "#ccc", // 设置边框颜色
        borderWidth: 1, // 设置边框宽度
        extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
        formatter: function (params) {
          let xAxisValue = params[0].axisValue; // 获取 x 轴时间
          let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
          params.forEach(function (param) {
            if (param.seriesName === t("equipmentDetail.lowSideVoltage")) {
              // 确保效率数据后面带有 % 单位
              tooltipStr += `${param.seriesName}: ${param.value} V \n`;
            } else {
              tooltipStr += `${param.seriesName}: ${param.value} ${currentUnit} \n`;
            }
          });
          return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
        },
      },
      grid: {
        top: "18%", // 上边距
        right: "2%", // 右边距
        bottom: "1%", // 下边距
        left: newLeft, // 左边距
        containLabel: true, // 是否包含坐标轴的标签
      },
      dataZoom: [
        // {
        //   type: "inside", // 内部缩放
        //   xAxisIndex: 0,
        //   start: 0,
        //   end: (7 / currTimeArr.length) * 100,
        //   zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
        //   moveOnMouseMove: true, // 允许鼠标拖动
        //   moveOnMouseWheel: false, // 禁止鼠标滚轮移动
        // },
      ],
    };
  } else {
    return {};
  }
};

const getMpptCurve = () => {
  nextTick(() => {
    if (moduleNumber.value == 0) {
      let params = {
        siteId: queryParams.value.siteId,
        slaveId: queryParams.value.slaveId,
        currTime: moduleChartRef.value.getTimeJson(),
      };
      apis.getMpptCurve(params).then((res) => {
        if (res.code == 200) {
          dataChartOfMpptCusver.value = setMpptCurve(res.data);
          console.log(
            "dataChartOfMpptCusver.value",
            dataChartOfMpptCusver.value
          );
        }
      });
    } else {
      let params = {
        siteId: queryParams.value.siteId,
        slaveId: queryParams.value.slaveId,
        currTime: moduleChartRef.value.getTimeJson(),
        mpptId: moduleNumber.value,
      };
      apis.getMpptModuleCurve(params).then((res) => {
        console.log("mppt模块曲线", res);
        if (res.code == 200) {
          dataChartOfMpptCusver.value = setMpptCurve(res.data);
        }
      });
    }
  });
};
const getMpptData = () => {
  if (moduleNumber.value == 0) {
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
    };
    apis.getMpptSummary(params).then((res) => {
      console.log("MPPT", res);
      if (res.code == 200) {
        dataListSummaryDataMPPT.value = res.data;
      }
    });
  } else {
    console.log("00000000000000000000000000");
    let params = {
      mpptId: moduleNumber.value,
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
    };
    apis.getMpptModuleData(params).then((res) => {
      console.log("mppt模块数据", res);
      if (res.code == 200) {
        dataListDataMPPTModule.value = res.data;
      }
    });
  }
};
const getPcsData = () => {
  if (moduleNumber.value == 0) {
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
    };
    apis.getPcsSummary(params).then((res) => {
      console.log("PCS", res);
      if (res.code == 200) {
        dataListSummaryDataPCS.value = res.data;
      }
    });
  } else {
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
      pcsId: moduleNumber.value,
    };
    apis.getPcsModuleData(params).then((res) => {
      console.log("resresresres", res);
      if (res.code == 200) {
        dataListModuleDataPCS.value = res.data;
      }
    });
  }
};

const getPcsCur = () => {
  if (moduleNumber.value == 0) {
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
      currTime: moduleChartRef.value.getTimeJson(),
    };
    apis.getPcsCurve(params).then((res) => {
      if (res.code == 200) {
        let acActivePowerArrTest = [];
        let currTimeArr = [];
        res.data.forEach((item) => {
          acActivePowerArrTest.push(Number(item.acActivePower));
        });
        let arr = calculateAverage(acActivePowerArrTest);
        let unit = powerUnit(arr, 1);
        let acActivePowerArr = []; // 储能功率
        res.data.forEach((item) => {
          currTimeArr.push(item.currTime);
          acActivePowerArr.push(
            formatPowerUnitOfUnit(item.acActivePower, unit)
          );
        });
        // 计算 Y 轴最大数值的字符长度
        const maxValue = Math.max(acActivePowerArr);
        const maxLength = maxValue.toString().length;
        // 根据字符长度动态调整 grid 的 left 值
        const baseLeft = -2; // 基础 left 百分比
        const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
        const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%
        if (currTimeArr.length > 0 && acActivePowerArr.length > 0) {
          const chartOption = {
            title: {
              text: unit,
              top: 10,
              left: 16,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
            legend: {
              icon: "rect",
              itemWidth: 12,
              itemHeight: 8,
              right: "5%",
              itemStyle: {
                borderRadius: 20, // 调整后的圆角值
                borderWidth: 0, // 设置边框宽度为0
              },
              textStyle: {
                // 设置图例文字的大小
                fontSize: 10,
                // 设置图例文字的颜色
                color: "#6e7180",
              },
              data: [
                {
                  name: t("equipmentDetail.totalAcActivePower"),
                  icon: "rect",
                  itemStyle: {
                    color: "#097BFE", // 对应储能功率折线图线条颜色
                  },
                },
              ],
            },
            xAxis: {
              type: "category",
              boundaryGap: false, // 确保折线图的起点和终点与坐标轴的两端对齐
              data: currTimeArr,
            },
            yAxis: {
              type: "value",
              axisLabel: {
                show: true,
                color: "#6e7180",
              },
              axisTick: {
                lineStyle: {
                  type: "dashed", // 设置 y 轴刻度线为虚线
                },
              },
              splitLine: {
                show: true,
                lineStyle: {
                  type: "dashed", // 设置 y 轴刻度线为虚线
                  color: "#6e7180", // 修改 x 轴网格横线颜色为红色
                },
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#6e7180",
                },
              },
            },
            series: [
              {
                name: t("equipmentDetail.totalAcActivePower"),
                data: acActivePowerArr,
                type: "line",
                smooth: true,
                lineStyle: {
                  color: "#097BFE", // 修改线条颜色为红色
                },
                symbol: "none", // 取消小圆点
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "#0E55AB", // 渐变起始颜色
                      },
                      {
                        offset: 1,
                        color: "#132238", // 渐变结束颜色
                      },
                    ],
                  },
                },
              },
            ],
            tooltip: {
              show: true,
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                // point: 鼠标位置，格式为 [x, y]
                // params: 提示框所对应的数据项
                // dom: 提示框的 DOM 节点
                // rect: 图表的 DOM 节点的矩形框信息
                // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
                let x = point[0];
                let y = point[1];
                let viewWidth = size.viewSize[0];
                let viewHeight = size.viewSize[1];
                let boxWidth = size.contentSize[0];
                let boxHeight = size.contentSize[1];

                // 确保 tooltip 在页面内完全显示
                if (x + boxWidth > viewWidth) {
                  x = viewWidth - boxWidth;
                }
                if (y - boxHeight < 0) {
                  y = boxHeight;
                }

                return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
              },
              backgroundColor: "#fff", // 设置背景颜色为白色
              borderColor: "#ccc", // 设置边框颜色
              borderWidth: 1, // 设置边框宽度
              extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
              formatter: function (params) {
                let xAxisValue = params[0].axisValue; // 获取 x 轴时间
                let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
                params.forEach(function (param) {
                  tooltipStr += `${param.seriesName}: ${param.value + unit} \n`;
                });
                return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
              },
            },
            grid: {
              top: "12%", // 上边距
              right: "2%", // 右边距
              bottom: "1%", // 下边距
              left: newLeft, // 左边距
              containLabel: true, // 是否包含坐标轴的标签
            },
            dataZoom: [
              // {
              //   type: "inside", // 内部缩放
              //   xAxisIndex: 0,
              //   start: 0,
              //   end: (7 / currTimeArr.length) * 100,
              //   zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
              //   moveOnMouseMove: true, // 允许鼠标拖动
              //   moveOnMouseWheel: false, // 禁止鼠标滚轮移动
              // },
            ],
          };
          summaryCurveOfPcs.value = chartOption;
        } else {
          summaryCurveOfPcs.value = {};
        }
      }
    });
  } else {
    let params = {
      siteId: queryParams.value.siteId,
      slaveId: queryParams.value.slaveId,
      pcsId: moduleNumber.value,
      currTime: moduleChartRef.value.getTimeJson(),
    };
    apis.getPcsModuleCurve(params).then((res) => {
      console.log("res获取模块曲线", res);
      if (res.code == 200) {
        let currTimeArr = [];
        let acActivePowerArr = [];
        let acReactivePowerArr = [];
        let acSignPowerArr = [];

        let acActivePowerArrTest = [];
        let acReactivePowerArrTest = [];
        let acSignPowerArrTest = [];

        res.data.forEach((item) => {
          acActivePowerArrTest.push(Number(item.acActivePower));
          acReactivePowerArrTest.push(Number(item.acReactivePower));
          acSignPowerArrTest.push(Number(item.acSignPower));
        });
        let arr = calculateAverage(
          ...acActivePowerArrTest,
          ...acReactivePowerArrTest,
          ...acSignPowerArrTest
        );
        let unit = powerUnit(arr, 1);

        res.data.forEach((item) => {
          currTimeArr.push(item.currTime);
          acActivePowerArr.push(
            formatPowerUnitOfUnit(Number(item.acActivePower), unit)
          );

          acReactivePowerArr.push(
            formatPowerUnitOfUnit(Number(item.acReactivePower), unit)
          );
          acSignPowerArr.push(
            formatPowerUnitOfUnit(Number(item.acSignPower), unit)
          );
        });
        if (
          currTimeArr.length > 0 &&
          acActivePowerArr.length > 0 &&
          acReactivePowerArr.length > 0 &&
          acSignPowerArr.length > 0
        ) {
          // 计算 Y 轴最大数值的字符长度
          const maxValue = Math.max(
            ...acActivePowerArr,
            ...acReactivePowerArr,
            ...acSignPowerArr
          );
          const maxLength = maxValue.toString().length;
          // 根据字符长度动态调整 grid 的 left 值
          const baseLeft = -2; // 基础 left 百分比
          const additionalLeft = maxLength * 2; // 每个字符增加 2% 的 left 值
          const newLeft = Math.min(baseLeft + additionalLeft, 30); // 最大不超过 30%

          const chartOption = {
            title: {
              text: unit,
              top: 10,
              left: 16,
              textStyle: {
                fontSize: 10, // 标题字体大小
                color: "#6E7180", // 标题字体颜色，这里设置为红色
              },
            },
            legend: {
              icon: "rect",
              itemWidth: 12,
              itemHeight: 8,
              right: "5%",
              itemStyle: {
                borderRadius: 20, // 调整后的圆角值
                borderWidth: 0, // 设置边框宽度为0
              },
              textStyle: {
                // 设置图例文字的大小
                fontSize: 10,
                // 设置图例文字的颜色
                color: "#6e7180",
              },
              data: [
                {
                  name: t("equipmentDetail.acActivePower"),
                  icon: "rect",
                  itemStyle: {
                    color: "#097BFE", // 对应储能功率折线图线条颜色
                  },
                },
                {
                  name: t("equipmentDetail.acApparentPower"),
                  icon: "rect",
                  itemStyle: {
                    color: "#9381F4", // 对应储能功率折线图线条颜色
                  },
                },
                {
                  name: t("equipmentDetail.acReactivePower"),
                  icon: "rect",
                  itemStyle: {
                    color: "#70F9BB", // 对应储能功率折线图线条颜色
                  },
                },
              ],
            },
            xAxis: {
              type: "category",
              boundaryGap: false, // 确保折线图的起点和终点与坐标轴的两端对齐
              data: currTimeArr,
            },
            yAxis: [
              {
                type: "value",
                axisLabel: {
                  show: true,
                  color: "#6e7180",
                },
                splitLine: {
                  show: true,
                  lineStyle: {
                    type: "dashed", // 设置 y 轴刻度线为虚线
                    color: "#6e7180", // 修改 x 轴网格横线颜色为红色
                  },
                },
                axisLine: {
                  show: true,
                  lineStyle: {
                    color: "#6e7180",
                  },
                },
              },
            ],
            series: [
              {
                name: t("equipmentDetail.acActivePower"),
                data: acActivePowerArr,
                type: "line",
                smooth: true,
                lineStyle: {
                  color: "#097BFE", // 修改线条颜色为红色
                },
                symbol: "none", // 取消小圆点
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "#286AC1", // 渐变起始颜色
                      },
                      {
                        offset: 1,
                        color: "#132742", // 渐变结束颜色
                      },
                    ],
                  },
                },
              },
              {
                name: t("equipmentDetail.acApparentPower"),
                data: acSignPowerArr,
                type: "line",
                smooth: true,
                lineStyle: {
                  color: "#9381F4", // 修改线条颜色为红色
                },
                symbol: "none", // 取消小圆点
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "#475582", // 渐变起始颜色
                      },
                      {
                        offset: 1,
                        color: "#19263E", // 渐变结束颜色
                      },
                    ],
                  },
                },
              },
              {
                name: t("equipmentDetail.acReactivePower"),
                data: acReactivePowerArr,
                type: "line",
                smooth: true,
                lineStyle: {
                  color: "#70F9BB", // 修改线条颜色为红色
                },
                symbol: "none", // 取消小圆点
                areaStyle: {
                  color: {
                    type: "linear",
                    x: 0,
                    y: 0,
                    x2: 0,
                    y2: 1,
                    colorStops: [
                      {
                        offset: 0,
                        color: "#335763", // 渐变起始颜色
                      },
                      {
                        offset: 1,
                        color: "#22344B", // 渐变结束颜色
                      },
                    ],
                  },
                },
              },
            ],
            tooltip: {
              show: true,
              trigger: "axis",
              position: function (point, params, dom, rect, size) {
                // point: 鼠标位置，格式为 [x, y]
                // params: 提示框所对应的数据项
                // dom: 提示框的 DOM 节点
                // rect: 图表的 DOM 节点的矩形框信息
                // size: 提示框的大小信息，格式为 {contentSize: [width, height], viewSize: [width, height]}
                let x = point[0];
                let y = point[1];
                let viewWidth = size.viewSize[0];
                let viewHeight = size.viewSize[1];
                let boxWidth = size.contentSize[0];
                let boxHeight = size.contentSize[1];

                // 确保 tooltip 在页面内完全显示
                if (x + boxWidth > viewWidth) {
                  x = viewWidth - boxWidth;
                }
                if (y - boxHeight < 0) {
                  y = boxHeight;
                }

                return [x, y - boxHeight]; // 将 tooltip 放到鼠标上方
              },
              backgroundColor: "#fff", // 设置背景颜色为白色
              borderColor: "#ccc", // 设置边框颜色
              borderWidth: 1, // 设置边框宽度
              extraCssText: "box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);", // 添加阴影效果
              formatter: function (params) {
                let xAxisValue = params[0].axisValue; // 获取 x 轴时间
                let tooltipStr = `${xAxisValue}\n`; // 将 x 轴时间添加到最上面一行
                params.forEach(function (param) {
                  tooltipStr += `${param.seriesName}: ${param.value + unit} \n`;
                });
                return tooltipStr.replace(/\n$/, ""); // 移除末尾 <br/>
              },
            },
            grid: {
              top: "12%", // 上边距
              right: "2%", // 右边距
              bottom: "1%", // 下边距
              left: newLeft, // 左边距
              containLabel: true, // 是否包含坐标轴的标签
            },
            dataZoom: [],
          };
          summaryCurveOfPcs.value = chartOption;
        } else {
          summaryCurveOfPcs.value = {};
        }
      }
    });
  }
};
</script>

<style lang="scss" scoped>
.detail {
  width: 100%;
  padding: 0 30rpx 30rpx 30rpx;
  box-sizing: border-box;
  :deep(.battery-container) {
    margin: 0 auto !important;
  }
  .header {
    width: 100%;
    padding: 0 20rpx;
    box-sizing: border-box;
    :deep(.u-tabs__wrapper__nav__item) {
      padding: 0 50rpx;
    }
    :deep(.u-tabs__wrapper__nav__line) {
      /* 自动布局 */
      display: flex;
      background: #64b7f6;
    }
  }
}

.pcs-list {
  width: 100%;
  margin: 30rpx 0;
  background: #132034;
  border-radius: 15rpx;
  padding: 32rpx;
  box-sizing: border-box;
  :deep(.u-cell__body) {
    padding: 39rpx 0 !important;
  }
  :deep(.u-cell__title-text) {
    font-family: Alibaba PuHuiTi 3;
    font-size: 32rpx;
    font-weight: normal;

    font-variation-settings: "opsz" auto;
    color: #eeeeee;
  }
  :deep(.u-cell__value) {
    font-family: Alibaba PuHuiTi 3;
    font-size: 32rpx;
    font-weight: 500;
    font-variation-settings: "opsz" auto;
    color: #ffffff;
  }
  :deep(.u-line) {
    border-color: #08121e !important;
  }
}
.detail-mppt-item {
  width: 100%;
  box-sizing: border-box;
  background: #132034;
  border-radius: 32rpx;
  margin-top: 30rpx;
  padding-top: 30rpx;
  padding-bottom: 40rpx;
  .row-detail {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-left: 30rpx;
    box-sizing: border-box;
    .row-detail-img {
      width: 80rpx;
      height: 80rpx;
      margin-right: 24rpx;
    }
    .number {
      font-family: D-DIN;
      font-size: 36rpx;
      font-weight: bold;
      color: #ffffff;
      .unit {
        font-family: Alibaba PuHuiTi 3;
        font-size: 20rpx;
        font-weight: normal;
        margin-top: 20rpx;
        font-variation-settings: "opsz" auto;
        font-feature-settings: "kern" on;
        color: #9e9e9e;
      }
    }
  }
}
.detail-dcdc-item {
  width: 100%;
  box-sizing: border-box;
  background: #132034;
  border-radius: 32rpx;
  margin-top: 30rpx;
  padding-top: 30rpx;
  padding-bottom: 40rpx;
  .row-detail {
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding-left: 30rpx;
    box-sizing: border-box;
    .row-detail-img {
      width: 80rpx;
      height: 80rpx;
      margin-right: 24rpx;
    }
    .number {
      font-family: D-DIN;
      font-size: 36rpx;
      font-weight: bold;
      color: #ffffff;
      .unit {
        font-family: Alibaba PuHuiTi 3;
        font-size: 20rpx;
        font-weight: normal;
        margin-top: 20rpx;
        font-variation-settings: "opsz" auto;
        font-feature-settings: "kern" on;
        color: #9e9e9e;
      }
    }
  }
}
.module-chart {
  margin-top: 24rpx;
}
</style>
